#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include     <sys/ioctl.h>               
#include     <sys/socket.h>               
#include     <net/if.h>               
#include     <netinet/in.h>               
#include     <net/if_arp.h>               
#include     <arpa/inet.h>       
#include     <unistd.h>     //for     close()  
#include "senddata.h"

int server_sockfd,client_sockfd;
int server_len,client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;


void initsock(char *pRemIP,unsigned short uRemPort,unsigned short uLocPort)
{
	//1.初始化SOCKET
	server_sockfd = socket(AF_INET, SOCK_DGRAM, 0);

	bzero(&server_address, sizeof(server_address)); //地址结构清零
	server_address.sin_family = AF_INET; //IPv4协议
	server_address.sin_addr.s_addr = htonl(INADDR_ANY);//内核指定地址
	server_address.sin_port = htons(uLocPort); //6800 端口PORT_SOCKET_SERVER
	server_len = sizeof(server_address);
	bind(server_sockfd,(struct sockaddr *)&server_address,server_len);

	bzero(&client_address, sizeof(client_address)); //地址结构清零
	client_address.sin_family = AF_INET; //IPv4协议
	client_address.sin_addr.s_addr = inet_addr(pRemIP); //IP地址 "192.168.1.126"
	client_address.sin_port = htons(uRemPort); //6801 端口PORT_SOCKET_CLIENT
	client_len = sizeof(client_address);

}

void senddata(BYTE* pPicBuf,int ilen,int flag)
{
	static BYTE m_uID = 1;
	int inum=ilen/SIZE_VIDEO_PACKED;
	int subid = 0;
	//int ipacklen = 0;

	int iSend = 0;
	int ibuflen = 0;
	
	AVIO_VIDEO vpack;
	
	int i=0;

	if(inum*SIZE_VIDEO_PACKED < ilen)
		inum++;

	for(i=0;i<inum;i++)
	{

		memset(&vpack,0,sizeof(AVIO_VIDEO));
		vpack.flag = flag;
		vpack.id = m_uID;
		vpack.subid = subid;
		vpack.data_size_total = ilen;

		//计算该报的数据长度

		if(ilen-i*SIZE_VIDEO_PACKED >= SIZE_VIDEO_PACKED)
			ibuflen = SIZE_VIDEO_PACKED;
		else
			ibuflen = ilen-i*SIZE_VIDEO_PACKED;
		
		vpack.data_size = ibuflen;
		memcpy(&vpack.data[0],pPicBuf+i*SIZE_VIDEO_PACKED,ibuflen);

		if(subid<255)
			subid++;
		else
			subid=0;

		ibuflen = sizeof(AVIO_VIDEO); // - SIZE_VIDEO_PACKED + vpack.data_size;

		//发送数据
		iSend = sendto(server_sockfd, &vpack, ibuflen, 0, (struct sockaddr *)&client_address, client_len);
		

		//iSend = m_socket.SendTo(&vpack,ibuflen,PORT_SOCKET_CLIENT,"192.168.1.126",0);
	}
	
	if(m_uID<255)
		m_uID++;
	else
		m_uID=1;

	//printf("Frame sent: len = %d id = %d  num = %d\n",iSend,vpack.id,inum);

}

